package com.xnx3.kefu.admin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.vo.ActionLogListVO;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.KefuJS;
import com.xnx3.kefu.core.util.MessageStorageUtil;
import com.xnx3.kefu.core.vo.KefuJSVO;

/**
 * 生成可以放到第三方网站的js
 * @author 管雷鸣
 */
@Controller(value="KefuAdminKefuJSController")
@RequestMapping("/kefu/admin/kefuJS/")
public class KefuJSController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;

	/**
	 * 获取当前客服的 kefuJS 信息
	 */
	@ResponseBody
	@RequestMapping("getKefuJS${api.suffix}")
	public KefuJSVO getKefuJS(HttpServletRequest request,Model model){
		KefuJSVO vo = new KefuJSVO();
		
		KefuJS kefuJS = sqlService.findById(KefuJS.class, getKefuId());
		if(kefuJS == null){
			kefuJS = new KefuJS();
			kefuJS.setId(getKefuId());
		}
		vo.setKefuJS(kefuJS);
	
		//获取其Kefu
		Kefu kefu = sqlCacheService.findById(Kefu.class, kefuJS.getId());
		vo.setKefu(kefu);
		
		ActionLogUtil.insert(request, "获取kefuJS", kefuJS.toString());
		return vo;
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("save${api.suffix}")
	public BaseVO save(Model model, HttpServletRequest request,
			KefuJS inputKefuJS){
		KefuJS kefuJS = sqlService.findById(KefuJS.class, getKefuId());
		if(kefuJS == null){
			kefuJS = new KefuJS();
			kefuJS.setId(getKefuId());
		}
		kefuJS.setColor(inputKefuJS.getColor());
		kefuJS.setBackgroundColor(inputKefuJS.getBackgroundColor());
		sqlService.save(kefuJS);
		
		refreshCache(kefuJS); //刷新缓存
		ActionLogUtil.insert(request, "保存kefuJS", kefuJS.toString());
		return success();
	}
	
	/**
	 * 刷新缓存相关
	 * @param kefuJS 有变动的kefuJS实体类
	 */
	private void refreshCache(KefuJS kefuJS){
		sqlCacheService.deleteCacheById(KefuJS.class, kefuJS.getId());
	}
}
